package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.cj.mobile.iabp.BuildConfig;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.dialog.PopupTipsDialog;
import com.cj.mobile.iabp.app.global.AccountManager;
import com.cj.mobile.iabp.app.global.Constant;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.EventBusTags;
import com.cj.mobile.iabp.di.component.DaggerLoginComponent;
import com.cj.mobile.iabp.di.module.LoginModule;
import com.cj.mobile.iabp.mvp.contract.LoginContract;
import com.cj.mobile.iabp.mvp.model.entity.AppUpdate;
import com.cj.mobile.iabp.mvp.model.entity.MainEvent;
import com.cj.mobile.iabp.mvp.presenter.LoginPresenter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qiangxi.checkupdatelibrary.CheckUpdateOption;
import com.qiangxi.checkupdatelibrary.Q;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {
    /*----------------------------------------------------------------控件信息----------------------------------------------------------------*/
    @BindView(R.id.activity_login)
    LinearLayout contentLayout;                                                                     // 界面总布局

    @BindView(R.id.txvi_loginactivity_pwdlogin)
    TextView txviPwdLogin;
    @BindView(R.id.imvi_loginactivity_pwdlogin_sign)
    ImageView imviPwdLogin;

    @BindView(R.id.txvi_loginactivity_codelogin)
    TextView txviCodeLogin;
    @BindView(R.id.imvi_loginactivity_codelogin_sign)
    ImageView imviCodeLogin;

    @BindView(R.id.edit_loginactivity_username)
    EditText edtTxtUsername;                                                                        // 用户名输入框

    @BindView(R.id.imvi_loginactivity_userclose_icon)
    ImageView imgviUserClose;                                                                       // 清空用户名输入框


    @BindView(R.id.txvi_loginactivity_tips_pwd)
    TextView txviPwdTips;

    @BindView(R.id.edit_loginactivity_password)
    EditText edtTxtPassword;                                                                        // 密码输入框
    @BindView(R.id.imvi_loginactivity_password_see)
    ImageView imgviPwdsee;                                                                          // 密码可见

    @BindView(R.id.txvi_loginactivity_sendsms)
    TextView txviSendSms;

    @BindView(R.id.btn_loginactivity_submit)
    Button btnLogin;                                                                                // 登录按钮

    @BindString(R.string.common_exit_app_tips)
    String commonTips;

    @BindView(R.id.txvi_loginactivity_seturl)
    TextView txviSetUrl;
    /*----------------------------------------------------------------业务信息----------------------------------------------------------------*/
    @Inject
    AccountManager accountManager;
    // 登录对话框
    private MaterialDialog mDialog;
    // 是否退出APP
    private boolean isExitAPP = false;
    // 登录方式：true 短信验证码、false 账号密码登录
    private boolean mSwitchLogin = false;
    // 密码是否可见
    private Boolean isVisible = false;

    @Override
    protected void onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        if (mDialog != null) {
            this.mDialog.dismiss();
        }

        if (isExitAPP) {
            if (mPresenter != null) {
                mPresenter.stopLocationService();
            }
        }
        super.onDestroy();
        this.mDialog = null;

        this.accountManager = null;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    /**
     * 关闭滑动返回
     */
    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            String phone = bundle.getString("phone");
            if (TextUtils.isEmpty(phone)) {
                setUsernName(accountManager.getAccount());
                setPassword(accountManager.getPassword());
            } else {
                // 从注册过来的
                setUsernName(phone);
            }
        }
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // 不需要默认事件
        getIntent().putExtra("isInitToolbar", true);
        // 获取传过来的值
        if (mPresenter != null) {
            mPresenter.getBundleValues(getIntent().getExtras());
        }

        edtTxtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int userSize = edtTxtUsername.getText().length();
                if (userSize > 0) {
//                    edtTxtUsername.setSelection(userSize);                                        // 设置光标
                    imgviUserClose.setVisibility(View.VISIBLE);                                     // 显示清空用户名按钮
                } else {
                    imgviUserClose.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        edtTxtPassword.setTypeface(Typeface.DEFAULT);
        edtTxtPassword.setTransformationMethod(new PasswordTransformationMethod());

        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.loginactivity_login_processtips).progress(true, 0).build();

        // 只有在测试环境才允许修改地址
        txviSetUrl.setVisibility(BuildConfig.DEBUG ? View.VISIBLE : View.GONE);
    }

    /**
     * 点击事件
     */
    @OnClick({
            R.id.imvi_loginactivity_userclose_icon,                                                 // 清空用户名输入框
            R.id.imvi_loginactivity_password_see,                                                   // 密码是否可见
            R.id.txvi_loginactivity_pwdlogin,                                                       // 切换成密码登录
            R.id.txvi_loginactivity_codelogin,                                                      // 切换成验证码登录
            R.id.txvi_loginactivity_sendsms,                                                        // 发送验证码
            R.id.btn_loginactivity_submit,                                                          // 登录
            R.id.txvi_loginactivity_seturl,                                                         // 设置服务地址
    })
    public void onClick(View v) {
        hideInput();
        switch (v.getId()) {
            case R.id.imvi_loginactivity_userclose_icon:                                            // 清空用户名输入框
                edtTxtUsername.setText("");
                break;
            case R.id.imvi_loginactivity_password_see:                                              // 密码是否可见
                if (isVisible) {
                    isVisible = false;
                    imgviPwdsee.setBackgroundResource(R.mipmap.icon_statistics_see);
                    edtTxtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    imgviPwdsee.setBackgroundResource(R.mipmap.icon_statistics_no_see);
                    isVisible = true;
                    edtTxtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                edtTxtPassword.setSelection(edtTxtPassword.length());
                break;
            case R.id.txvi_loginactivity_pwdlogin:                                                  // 切换成密码登录
                switchLogin(false);
                break;
            case R.id.txvi_loginactivity_codelogin:                                                 // 切换成验证码登录
                switchLogin(true);
                break;
            case R.id.txvi_loginactivity_sendsms:                                                   // 发送验证码
                if (!CommonUtils.isDoubleClick()) {
                    String username = edtTxtUsername.getText().toString().trim();
                    if ("".equals(username)) {
                        showMessage("请输入手机号");
                        return;
                    }
                    if (!RegexUtils.isMobileSimple(username)) {
                        showMessage(ArmsUtils.getString(getActivity(), R.string.loginactivity_login_usercodenotnull));
                        return;
                    }

                    if (mPresenter != null) {
                        mPresenter.sendSMS(username);
                    }
                }
                break;
            case R.id.btn_loginactivity_submit:                                                     // 登录
                String username = edtTxtUsername.getText().toString().trim();
                String password = edtTxtPassword.getText().toString().trim();
                if (mPresenter != null) {
                    mPresenter.btnLoginOnClick(username, password, mSwitchLogin);
                }
                break;
            case R.id.txvi_loginactivity_seturl:                                                    // 设置服务地址
                ActivityUtils.startActivity(SetServerAddressActivity.class);
                break;
        }
    }

    /**
     * 切换登录方式
     */
    private void switchLogin(boolean value) {
        mSwitchLogin = value;
        if (mSwitchLogin) {                                                                         // 账号密码登录
            // 提示可以切换短信验证码
            txviPwdLogin.setTextSize(16);
            txviPwdLogin.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            imviPwdLogin.setVisibility(View.INVISIBLE);

            txviCodeLogin.setTextSize(20);
            txviCodeLogin.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            imviCodeLogin.setVisibility(View.VISIBLE);

            edtTxtUsername.setHint("请输入手机号");
            edtTxtUsername.setInputType(InputType.TYPE_CLASS_NUMBER);

            txviPwdTips.setText("验证码");
            edtTxtPassword.setHint("请输入验证码");
            edtTxtPassword.setInputType(InputType.TYPE_CLASS_NUMBER);
            edtTxtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

            txviSendSms.setVisibility(View.VISIBLE);
            imgviPwdsee.setVisibility(View.GONE);
        } else {                                                                                    // 短信验证码
            // 提示可以切换账号密码登录
            txviPwdLogin.setTextSize(20);
            txviPwdLogin.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            imviPwdLogin.setVisibility(View.VISIBLE);

            txviCodeLogin.setTextSize(16);
            txviCodeLogin.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            imviCodeLogin.setVisibility(View.INVISIBLE);

            edtTxtUsername.setHint("请输入用户名/手机号");
            edtTxtUsername.setInputType(InputType.TYPE_CLASS_TEXT);

            txviPwdTips.setText("密码");
            edtTxtPassword.setHint("请输入密码");
            edtTxtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
            edtTxtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

            txviSendSms.setVisibility(View.GONE);
            imgviPwdsee.setVisibility(View.VISIBLE);
        }

        // 切换时清空数据
        edtTxtPassword.setText("");
    }

    /**
     * 隐藏软键盘
     */
    private void hideInput() {
        KeyboardUtils.hideSoftInput(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        hideInput();
        return super.onTouchEvent(event);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {
        if (mDialog != null)
            mDialog.show();
    }

    @Override
    public void hideLoading() {
        if (mDialog != null)
            mDialog.cancel();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getApplicationContext(), message);
    }

    @Override
    public void killMyself() {
        finish();
    }

    /**
     * 登录成功    回调
     */
    @Subscriber(tag = EventBusTags.HOME_TAG, mode = ThreadMode.POST)
    private void eventBusEvent(MainEvent mainEvent) {
        if (mainEvent.getCode() == EventBusTags.LOGIN_SUCC_TAG)
            killMyself();
    }

    /**
     * 忘记密码    回调
     */
    @Subscriber(tag = "ForgotPassword_tag", mode = ThreadMode.POST)
    private void updateUser(String account) {
        setUsernName(account);

        edtTxtPassword.setText("");
        edtTxtPassword.setFocusable(true);
        edtTxtPassword.setFocusableInTouchMode(true);
        edtTxtPassword.requestFocus();
    }

    /**
     * 监听返回键
     */
    @Override
    public void onBackPressed() {
        PopupTipsDialog.PopupClick popupClick = click -> {
            if (click) {
                isExitAPP = true;
                AppUtils.exitApp();
            }
        };
        PopupTipsDialog phoneDialog = new PopupTipsDialog(this, commonTips, popupClick);
        phoneDialog.showAtLocation(contentLayout, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    @Override
    public void setUsernName(String usernName) {
        edtTxtUsername.setText(usernName);
        if (!TextUtils.isEmpty(usernName)) {
            // 设置光标
            edtTxtUsername.setSelection(usernName.length());
        }

    }

    @Override
    public void setPassword(String password) {
        edtTxtPassword.setText(password);
    }

    @Override
    public void jumbToMain() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            bundle.putBoolean("isLoginJump", true);
            ActivityUtils.startActivity(bundle, MainActivity.class);
        } else {
            ActivityUtils.startActivity(MainActivity.class);
        }
    }

    @Override
    public void askDialog(AppUpdate info) {
        Q.show(this, new CheckUpdateOption.Builder()
                .setAppName(info.getName())
                .setFileName("/" + info.getFileName())
                .setFilePath(Constant.APP_UPDATE_PATH)
//                .setImageUrl("http://imgsrc.baidu.com/imgad/pic/item/6c224f4a20a446233d216c4f9322720e0cf3d730.jpg")
                .setImageResId(R.mipmap.icon_upgrade_logo)
                .setIsForceUpdate(info.getForce() == 1)
                .setNewAppSize(info.getNewAppSize())
                .setNewAppUpdateDesc(info.getNewAppUpdateDesc())
                .setNewAppUrl(info.getFilePath())
                .setNewAppVersionName(info.getVerName())
                .setNotificationSuccessContent("下载成功，点击安装")
                .setNotificationFailureContent("下载失败，点击重新下载")
                .setNotificationIconResId(R.mipmap.ic_launcher)
                .setNotificationTitle(getString(R.string.app_name))
                .setMode(2)
                .build(), (view, imageUrl) -> {
            // 下载图片
//            view.setScaleType(ImageView.ScaleType.FIT_XY);
//            mImageLoader.loadImage(getActivity(),
//                    ImageConfigImpl
//                            .builder()
//                            .url(imageUrl)
//                            .imageView(view)
//                            .build());
        });
    }

    @Override
    public void onDisableSendVerificationCodeButton() {
        txviSendSms.setEnabled(false);
    }

    @Override
    public void onEnableSendVerificationCodeButton() {
        txviSendSms.setEnabled(true);
        // 重新设置按钮“提示”
        txviSendSms.setText(R.string.forgotpasswordactitivy_send_the_code);
    }

    @Override
    public void setCountDownTips(String str) {
        // 显示倒计时
        txviSendSms.setText(str);
    }

    @Override
    public void onDisableClick() {
        btnLogin.setEnabled(false);
        btnLogin.setClickable(false);
    }

    @Override
    public void onEnableClick() {
        btnLogin.setEnabled(true);
        btnLogin.setClickable(true);
    }
}
